<template>
  <view class="home-page2">
    <Navbar :title="page_title" background="#fff">
    </Navbar>
    <view class="banner-box">
      <!-- 轮播图 -->
      <view class="swiper-container">
        <swiper class="swiper" indicator-dots="true" autoplay="true" interval="3000" duration="500" circular="true">
          <swiper-item @click="clickBanner(index)"  v-for="(item, index) in bannerList" :key="index">
            <image :src="item.image" class="banner-image" mode="aspectFill"></image>
          </swiper-item>
        </swiper>
      </view>

      <!-- 金刚区导航 -->
      <view class="nav-grid">
        <view class="nav-item" v-for="(item, index) in navList" :key="index" @click="navigateTo(item.path)">
          <image :src="item.icon" class="nav-icon" mode="aspectFit"></image>
          <text class="nav-text">{{ item.name }}</text>
        </view>
      </view>
    </view>
    <view class="notice-box">
      <u-notice-bar speed="120" border-radius="8" bg-color="rgba(255, 195, 0, .1)" color="#333" mode="horizontal" :list="notices"></u-notice-bar>
    </view>

    <!-- 今日推荐产品 -->
    <view class="recommend-section" v-if="recommendList.length > 0">
      <view class="section-header">
        <text class="section-title">今日推荐</text>
        <!-- <text class="section-more" @click="goToTravel">查看更多</text> -->
      </view>
      <view class="recommend-list">
        <view
          class="recommend-item"
          v-for="travel in recommendList"
          :key="travel.id"
          @click="goToTravelDetail(travel.id)"
        >
          <view class="travel-image-wrapper">
            <image
              :src="travel.cover || '/static/image/logo.png'"
              class="travel-image"
              mode="aspectFill"
              lazy-load
              @error="onImageError"
            ></image>
          </view>
          <view class="travel-info">
            <view class="travel-header">
              <text class="travel-name">{{ travel.name }}</text>
              <view class="travel-price-section">
                <text class="travel-sales">已售 {{ travel.sales || 0 }}</text>
                <view class="price-info">
                  <text class="travel-price">{{ travel.price_text || 0 }}元/人起</text>
                  <text class="travel-price-tag" v-if="userInfo.user_type === 3">佣金{{ travel.share_price || 0 }}元</text>
                </view>
              </view>
            </view>
            <!-- <view class="travel-meta">
              <text class="travel-stock" v-if="getStockStatus(travel)">{{ getStockStatus(travel) }}</text>
            </view> -->
          </view>
        </view>
      </view>
    </view>
<!--    <view class="course-section" @click="toCustom">-->
<!--      <image src="https://diandian-1300713889.cos.ap-shanghai.myqcloud.com/1753499903326_gi4c5g9f.png" class="course-bg" mode="widthFix"></image>-->
<!--    </view>-->

    <u-tabbar @change="beforeSwitch" active-color="#FFC300" inactive-color="#333" v-model="current" :list="tabbarList" icon-size="55" height="120rpx" :mid-button="false"></u-tabbar>
  </view>
</template>

<script>
import Navbar from "../../components/Navbar.vue";
import api from "../../config/api.js";

export default {
	// 分享给朋友
	onShareAppMessage() {
		return {

		}
	},
  components: {Navbar},
  data() {
    return {
      current: 0,
      // 轮播图数据
      bannerList: [],
      // 金刚区导航数据
      navList: [],
      notices: [],
      // 今日推荐产品列表
      recommendList: [],
      page_title: ''
    }
  },
  onShow() {
    this.loadNoticeData();
    this.loadBannerData();
    this.loadTravelCategoryData();
    this.loadRecommendData();
    this.$api.getConfigByKey('page_title').then(res => {
      this.page_title = res.value
    })

    this.updateParentUserId()
  },
  methods: {
    getSharePrice(skus) {
      if (skus && skus.length > 0) {
        // 最高的佣金
        return skus.reduce((min, sku) => Math.min(min, sku.share_price), 0);
      }
      return 0;
    },
    toCustom() {
      this.$goPage({
        url: '/pages/travelCustom/travelCustom'
      })
    },
    // 加载公告数据
    loadNoticeData() {
      const params = {
        position: 'interview', // 笔试页面
        status: 1, // 只获取启用的公告
      };

      api.getNoticeList(params).then(response => {
        if (response && response.length > 0) {
          // 将公告标题提取为数组
          this.notices = response.map(item => item.title);
        }
      });
    },

    // 加载轮播图数据
    loadBannerData() {
      const params = {
        // position: 'written', // 笔试页面
        status: 1, // 只获取启用的轮播图
      };

      api.getBannerList(params).then(response => {
        if (response && response.length > 0) {
          // 将后端数据映射为前端需要的格式
          this.bannerList = response.map(item => ({
            id: item.id,
            image: item.image_url,
            url: item.link_url,
            product_id: item.product_id
          }));
        }
      });
    },

    // 加载旅行分类数据
    loadTravelCategoryData() {
      api.getTravelCategoryList().then(async response => {
        if (response && response.length > 0) {
          // 定制申请logo、名称
          const customApply = await this.$api.getConfigByKey('custom_apply_title')
          const customApplyLogo = await this.$api.getConfigByKey('custom_apply_logo')
          // 特产商城logo、名称
          const productMall = await this.$api.getConfigByKey('product_mall_title')
          const productMallLogo = await this.$api.getConfigByKey('product_mall_logo')
          // 将后端数据映射为前端需要的格式
          this.navList = [
              ...response.map(item => ({
                name: item.name,
                icon: item.cover || '', // 使用封面图片作为图标，如果没有则使用默认图标
                path: `/pages/travel/travel?categoryId=${item.id}` // 跳转到旅行商品列表页面并传递分类ID
              }))
          ]
          if (customApply && customApply) {
            this.navList.push({
              name: customApply.title || '定制申请',
              icon: customApplyLogo.value || '/static/home/1.png',
              path: '/pages/travelCustom/travelCustom',
            })
          }
          if (productMall && productMall) {
            this.navList.push({
              name: productMall.title || '特产商城',
              icon: productMallLogo.value || '/static/home/1.png',
              path: '/pages/product/product',
            })
          }
        }
      });
    },

    // 加载今日推荐数据
    loadRecommendData() {
      const params = {
        status: 1, // 只获取启用的旅行商品
        is_virtual: 1, // 虚拟产品
        sort: 'price_text,asc'
      };

      api.getTravelList(params).then(response => {
        this.recommendList = response
      }).catch(error => {
        console.error('加载今日推荐数据失败:', error);
      });
    },

    // 获取最低价格
    getMinPrice(travel) {
      // 如果旅行商品有SKU，显示最低价格
      if (travel.skus && travel.skus.length > 0) {
        const minPriceSku = travel.skus.reduce((min, sku) =>
          sku.price < min.price ? sku : min
        );
        return minPriceSku.price || 0;
      }
      // 否则显示旅行商品基础价格
      return travel.price || 0;
    },

    // 获取原价
    getOriginalPrice(travel) {
      // 如果旅行商品有SKU，显示最高原价
      if (travel.skus && travel.skus.length > 0) {
        const maxOriginalPriceSku = travel.skus.reduce((max, sku) =>
          (sku.original_price || 0) > (max.original_price || 0) ? sku : max
        );
        return maxOriginalPriceSku.original_price || 0;
      }
      // 否则显示旅行商品原价
      return travel.original_price || travel.price || 0;
    },

    // 获取库存状态
    getStockStatus(travel) {
      // 如果旅行商品有SKU，计算总库存
      if (travel.skus && travel.skus.length > 0) {
        const totalStock = travel.skus.reduce((sum, sku) => sum + (sku.stock || 0), 0);
        if (totalStock <= 0) {
          return '无货';
        } else if (totalStock < 10) {
          return '库存紧张';
        }
      } else {
        // 否则使用旅行商品基础库存
        if (travel.stock !== undefined) {
          if (travel.stock <= 0) {
            return '无货';
          } else if (travel.stock < 10) {
            return '库存紧张';
          }
        }
      }
      return '';
    },

    // 图片加载错误处理
    onImageError(e) {
      console.log('图片加载失败:', e);
    },

    // 跳转到旅行商品详情
    goToTravelDetail(travelId) {
      console.log('跳转到旅行商品详情:', travelId);
      uni.navigateTo({
        url: `/pages/travel/detail?id=${travelId}`
      });
    },

    // 跳转到旅行商品列表
    goToTravel() {
      uni.navigateTo({
        url: '/pages/travel/travel'
      });
    },

	  clickBanner(e) {
      // 获取当前点击的轮播图索引
      const banner = this.bannerList[e];
      if (banner.product_id) {
        // 产品详情页
        uni.navigateTo({
          url: `/pages/product/detail?id=${banner.product_id}`
        });
      }
      return
      if (banner && banner.url) {
        // 如果有链接，则跳转
        if (banner.url.startsWith('/pages/')) {
          // 内部页面跳转
          uni.navigateTo({
            url: banner.url
          });
        } else if (banner.url.startsWith('http')) {
          // 外部链接
          uni.navigateTo({
            url: `/pages/webview/webview?url=${encodeURIComponent(banner.url)}`
          });
        } else if (banner.product_id) {
          // 产品详情页
          uni.navigateTo({
            url: `/pages/product/detail?id=${banner.product_id}`
          });
        }
      }
	  },
    // 导航跳转
    navigateTo(path) {
      uni.navigateTo({
        url: path
      });
    },
    // 金刚功能区跳转
    navigateToFeature(path) {
      uni.navigateTo({
        url: path
      });
    }
  },

  onShareAppMessage() {
  },
  onShareTimeline() {
  },
}
</script>

<style lang="scss">
.home-page2 {
  min-height: 100vh;
  overflow: visible;
  padding-bottom: 60rpx;
  position: relative;
  z-index: 1;
  background-color: #f5f5f5;

  .course-section {
    padding: 24rpx;

    .course-bg {
      width: 100%;
      height: 240rpx;
    }
  }

  .banner-box {
    border-radius: 0 0 32rpx 32rpx;
    background: #FFFFFF;
    display: flex;
    flex-direction: column;
    padding: 20rpx;

    // 轮播图样式
    .swiper-container {
      border-radius: 12rpx;
      overflow: hidden;

      .swiper {
        height: 300rpx;

        .banner-image {
          width: 100%;
          height: 100%;
        }
      }
    }

    // 金刚区导航样式
    .nav-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      grid-gap: 18rpx;
      .nav-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding-top: 16rpx;

        .nav-icon {
          width: 90rpx;
          height: 90rpx;
          margin-bottom: 16rpx;
        }

        .nav-text {
          font-size: 26rpx;
          color: #333333;
          text-align: center;
          line-height: 1.2;
        }
      }
    }
  }

  .notice-box {
    padding: 24rpx;
    border-radius: 16rpx;
  }

  // 今日推荐区域
  .recommend-section {
    margin: 24rpx;
    background: #FFFFFF;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-top: 0;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12rpx;

      .section-title {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
      }

      .section-more {
        font-size: 26rpx;
        color: #FFC300;
        cursor: pointer;

        &:active {
          opacity: 0.8;
        }
      }
    }

    .recommend-list {
      .recommend-item {
        display: flex;
        background: #FFFFFF;
        border-radius: 8rpx;
        margin-bottom: 12rpx;
        padding: 12rpx 0;
        cursor: pointer;
        border-bottom: 1rpx solid #f0f0f0;
        padding-bottom: 28rpx;

        &:last-child {
          margin-bottom: 0;
          border-bottom: none !important;
        }

        &:active {
          background: #f8f8f8;
        }

        .travel-image-wrapper {
          width: 150rpx;
          margin-right: 24rpx;
          border-radius: 12rpx;
          overflow: hidden;
          background: #f8f8f8;

          .travel-image {
            width: 100%;
            height: 100%;
          }
        }

        .travel-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          height: 180rpx;
          .travel-header {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
            flex-grow: 1;
            .travel-name {
              font-size: 28rpx;
              color: #333333;
              line-height: 1.4;
              margin-bottom: 16rpx;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              overflow: hidden;
              word-break: break-all;
            }

            .travel-price-section {
              display: flex;
              align-items: flex-end;
              justify-content: space-between;

              .price-info {
                display: flex;
                flex-direction: column;
                align-items: flex-end;

                .travel-price {
                  font-size: 24rpx;
                  color: #ff4d4f;
                  font-weight: bold;
                  margin-right: 12rpx;
                }
                .travel-price-tag {
                  font-size: 20rpx;
                  background-color: #FFC300;
                  padding: 4rpx 12rpx;
                  border-radius: 8rpx;
                  margin-top: 4rpx;
                }

                .travel-original-price {
                  font-size: 24rpx;
                  color: #999999;
                  text-decoration: line-through;
                }
              }

              .travel-sales {
                font-size: 24rpx;
                color: #666666;
              }
            }
          }

          .travel-meta {
            display: flex;
            justify-content: flex-end;
            align-items: center;

            .travel-stock {
              font-size: 24rpx;
              color: #ff4d4f;
            }
          }
        }
      }
    }
  }

  // 金刚功能区样式
  .feature-section {
    padding: 0 24rpx;
    border-radius: 16rpx;

    .feature-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      grid-gap: 24rpx;
      .feature-card {
        height: 180rpx;
        border-radius: 32rpx;
        box-sizing: border-box;
        position: relative;

        .feature-title {
          color: #fff;
          font-size: 30rpx;
          font-weight: bold;
          margin-bottom: 16rpx;
          text-align: left;
          padding: 24rpx 12rpx;
          position: relative;
          z-index: 2;
        }

        .feature-icon {
          position: absolute;
          left: 0;
          top: 0;
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
